package com.hepinghospital.user.ui.kotlin

import android.Manifest
import android.annotation.SuppressLint
import android.annotation.TargetApi
import android.app.ActivityManager
import android.os.Build
import android.os.Handler
import android.text.TextUtils
import androidx.annotation.RequiresApi
import com.ainemo.sdk.otf.NemoSDK
import com.ainemo.sdk.otf.NemoSDKInitCallBack
import com.ainemo.sdk.otf.Settings
import com.ainemo.sdk.otf.VideoConfig
import com.gyf.immersionbar.ImmersionBar
import com.hepinghospital.user.R
import com.hepinghospital.user.base.BaseActivity
import com.hepinghospital.user.base.BaseApplication
import com.hepinghospital.user.ui.MainActivity
import com.hepinghospital.user.ui.activity.userinfo.LoginActivity
import com.hepinghospital.user.ui.dialog.ApplyPermissionDialog
import com.hepinghospital.user.ui.dialog.PermissionDialog
import com.hepinghospital.user.util.PermissionsChecker
import com.hepinghospital.user.util.ToastUtil
import com.rest.business.RestProxy
import com.rest.client.RestClient
import com.rest.observer.BaseObserver
import com.rest.response.LoginResponse
import com.tbruyelle.rxpermissions2.RxPermissions
import jz.joyoung.robot.util.AES128
import jz.joyoung.robot.util.LogUtil
import jz.joyoung.robot.util.PreferencesHelper
import jz.joyoung.robot.util.UtilString

/**
 * 欢迎页
 * Created by lbj on 2021/10/11 9:32
 */
class WelcomeActivity : BaseActivity() {
    private lateinit var mPermissionDialog: PermissionDialog
    private var accessToken: String? = null

    // 所需的全部权限
    val permissions = arrayOf(Manifest.permission.READ_PHONE_STATE)

    private lateinit var mPermissionsChecker: PermissionsChecker // 权限检测器

    override fun initData() {
        val userId: String?
        val isFirstInstall: Boolean

        with(PreferencesHelper.getInstance()) {
            accessToken = getString(this@WelcomeActivity, "accessToken")
            userId = getString(this@WelcomeActivity, "userId")
            isFirstInstall = getBoolean(this@WelcomeActivity, "isFirstInstall", true)
            BaseApplication.xyAccount = getString(this@WelcomeActivity, "xyAccount")
            BaseApplication.xyPassword = getString(this@WelcomeActivity, "xyPassword")
            RestClient.getInstance().token = accessToken
            BaseApplication.currentUserId = userId
        }
        if (isFirstInstall) { //第一次安装弹出隐私
            showPermissionDialog()
        } else {
            init()
        }
    }

    override fun getLayoutResource(): Int = R.layout.aty_welcome

    override fun initViews() {}

    override fun doBeforeSetcontentView() {
        ImmersionBar.with(this).keyboardEnable(true).fitsSystemWindows(false).statusBarColor(R.color.white).navigationBarColor(R.color.black).autoDarkModeEnable(true).init()
    }

    private fun showPermissionDialog() {
        mPermissionDialog = PermissionDialog.newInstance()
        mPermissionDialog.show(supportFragmentManager, "mPermissionDialog")
        mPermissionDialog.setmListener(object : PermissionDialog.OnItemClickListener {
            override fun onConfirm() {
                init()
//                checkPermission()
            }

            override fun onCancel() {
                ToastUtil.showToastCenter(mContext, "同意后可继续使用")
                exitAPP()
            }
        })
    }

    @SuppressLint("CheckResult")
    fun checkPermission() {
        mPermissionsChecker = PermissionsChecker(mContext)
        // 缺少权限时, 进入权限配置页面
        if (mPermissionsChecker.lacksPermissions(*permissions)) {
            val applyPermissionDialog = ApplyPermissionDialog.newInstance("1", true)

            applyPermissionDialog.show(supportFragmentManager, "applyPermissionDialog")
            applyPermissionDialog.setmListener(object : ApplyPermissionDialog.OnItemClickListener {
                @RequiresApi(Build.VERSION_CODES.O)
                override fun onConfirm() {
                    val permissions = RxPermissions(this@WelcomeActivity)
                    permissions.request(Manifest.permission.READ_PHONE_STATE)
                            .subscribe { aBoolean: Boolean ->
                                LogUtil.e(TAG, "request permission result:$aBoolean")
//                                init()
                                startActivity(GuideActivity::class.java)
                            }
                }

                override fun onCancel() {}
            })
        } else {
            init()
        }
    }

    private fun toLoginActivity() {
        Handler().postDelayed({
            startActivity(LoginActivity::class.java)
            finish()
        }, 1000)
    }

    fun init() {
        val settings = Settings("3e816492058911e7a31d000c29971af5")
        settings.privateCloudAddress = "39.172.69.238:7443"
        settings.isUiNeedSpeakers = true
        settings.videoMaxResolutionTx = VideoConfig.VD_1280x720
        settings.defaultCameraId = 1
        NemoSDK.getInstance().init(this, settings, object : NemoSDKInitCallBack {
            override fun nemoSdkInitSuccess() {
                LogUtil.e("小鱼SDK初始化成功")
            }

            override fun nemoSdkInitFail(s: String, s1: String) {
                LogUtil.e("SDK初始化失败")
            }
        })
        PreferencesHelper.getInstance().set(mContext, "isFirstInstall", false)
        if (UtilString.isEmpty(accessToken)) {
            toLoginActivity()
        } else {
            login()
        }
    }

    private fun login() {
        val username = PreferencesHelper.getInstance().getString(this, "username")
        val password = PreferencesHelper.getInstance().getString(this, "password")
        if (TextUtils.isEmpty(username) || TextUtils.isEmpty(password)) {
            startActivity(LoginActivity::class.java)
            this@WelcomeActivity.finish()
            return
        }
        try {
            RestProxy.getInstance().login(AES128.encryptStringAES(username, "7t3e506jaa10xbd4"), AES128.encryptStringAES(password, "7t3e506jaa10xbd4"), "", object : BaseObserver<LoginResponse>() {
                override fun onError(e: Throwable) {
                    startActivity(LoginActivity::class.java)
                    this@WelcomeActivity.finish()
                }

                override fun onSuccess(loginResponse: LoginResponse) {
                    checkServiceRunning(mContext)
                    BaseApplication.currentUserId = loginResponse.userId
                    BaseApplication.name = loginResponse.name
                    BaseApplication.avatar = loginResponse.avatar
                    BaseApplication.sex = loginResponse.sex
                    BaseApplication.userType = loginResponse.hosType
                    RestClient.getInstance().token = loginResponse.token
                    startActivity(MainActivity::class.java)
                    this@WelcomeActivity.finish()
                }
            })
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    private fun exitAPP() {
        val activityManager = mContext.applicationContext.getSystemService(ACTIVITY_SERVICE) as ActivityManager
        val appTaskList = activityManager.appTasks
        for (appTask in appTaskList) {
            appTask.finishAndRemoveTask()
        }
    }
}